package xyz.riceball.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import xyz.riceball.framework.core.auth.DefaultNotCheckUrlCustomizer;
import xyz.riceball.security.authentication.RiceBallAuthenticationProvider;

import java.util.Set;

/**
 * <p>
 * 权限配置
 * RiceBall会根据SpringSecurity默认实现一套权限控制
 * </p>
 *
 * @author xiaovcloud
 * @since 2022/4/25 00:18
 */
@Configuration
@EnableWebSecurity
public class RiceBallSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.apply(new RiceBallHttpConfigurer());
    }

    @Override
    public void configure(WebSecurity web) {
        //忽略权限校验的地址，需要手动配置NotCheckRightUrlCustomizer
        // 这是一个bean
        DefaultNotCheckUrlCustomizer notCheckUrlCustomizer = new DefaultNotCheckUrlCustomizer();
        Set<String> webIgnoring = notCheckUrlCustomizer.getNotCheckRightUrls();
        if (webIgnoring != null) {
            web.ignoring().antMatchers(webIgnoring.toArray(new String[0]));
        }
        //放行swagger
        web.ignoring().antMatchers("/error", "/favicon.ico",
                "/doc.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        RiceBallAuthenticationProvider authenticationProvider = new RiceBallAuthenticationProvider();
        auth.authenticationProvider(authenticationProvider)
                .jdbcAuthentication().passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String encode = bc.encode("111111");
        System.out.println(encode);

        boolean matches = bc.matches("111111", encode);
        System.out.println(matches);
    }

}
